<?php
/**
 * @author GhostWei
 * @date Sep 7, 2012
 */
class controller_www_account extends front_controller_panel {
	
	protected $referer = null;
	public function init() {
		if(!parent::init()) {
			return;
		}
		if($this->view->referer === null) {
			$this->view->referer = $this->getRequest()->getHeader('referer');
		}
		$this->referer = $this->view->referer;
	}
	
	public function action_index() {
		if($this->login()) {
			return false;
		}
		$this->_crumbs()->addPage(system_nav_page::create($this->language('用户中心'))->setRoute('account/signup'));
		$this->layout()->setLayout('layout/uc');
		$this->render();
	}
	
	public function action_passport() {
		if(!system_passport_instance::getInstance()->getSession()->getId()) {
			$this->_goRoute('account/login');
		}
		$this->_crumbs()->addPage(system_nav_page::create($this->language('登录'))->setRoute('account/passport'));
		$passport = system_passport_instance::getRow(system_passport_instance::getInstance()->getSession()->getId());

		$this->view->expires = 1;
		$row = $this->user;
		if($this->getRequest()->isPost()) {
			$this->referer = $this->_post('referer');
			$this->view->expires = $expires = intval($this->_post('expires'));
			try {
				system_db::getAdapter()->beginTransaction();
				$pwd = $this->_post('password');
				$ip = $this->getRequest()->getClientIp(true);
				$secure = $this->_post('secure');
				$gender = intval($this->_post('gender'));
				
				$row->setCredential(md5($pwd));
				$row->setSecure($secure);
				$row->setGender($gender);
				$row->setLastupip($ip);
				$row = $row->login();
				system_db::getAdapter()->commit();
				
				$this->_login($row, $secure, $expires);
				$this->_redirector($this->referer);
			} catch (Exception $e) {
				system_db::getAdapter()->rollBack();
				$this->view->referer = $this->referer;
				$this->view->throwException = $e;
			}
		}
		$this->view->row = $row;
		$this->layout()->setLayout('layout/uc');
		$this->render();
	}
	
	public function action_signup() {
		$this->_crumbs()->addPage(system_nav_page::create($this->language('用户注册'))->setRoute('account/signup'));
		$this->view->expires = 1;
		$concept = new community_member_concept($this->lang);
		$row = $concept->create();
		if($this->getRequest()->isPost()) {
			$source = null;
			$this->referer = $this->_post('referer');
			if(1 && $clientSource = $this->_post('oauth')) {
				$this->view->source = $source = new system_setting_oauth($clientSource);
			}
			$this->view->access_token = $this->_post('access_token');
			$this->view->avatar = $this->_post('avatar');
			$this->view->uid = $this->_post('uid');
			$this->view->expires = $expires = intval($this->_post('expires'));
			try {
				system_db::getAdapter()->beginTransaction();
				$email = trim($this->_post('account'));
				if(!($nickname = trim($this->_post('nickname')))) {
					$nickname = preg_replace('/^([^@]+)@(.*)/i', '$1', $email);
				}
				$ip = $this->getRequest()->getClientIp(true);
				$pwd = $this->_post('password');
				$pwd1 = $this->_post('password1');
				$secure = $this->_post('secure');
				$gender = intval($this->_post('gender'));
				
				$row->setIdentity($email);
				$row->setEmail($email);
				$row->setNickname($nickname);
				$row->setGender($gender);
				$row->setCredential(md5($pwd));
				$row->setSecure($secure);
				$row->setCreationip($ip);
				if(strlen($pwd) < 6) {
					throw new community_exception('密码过于简单，长度必须大于 6 位');
				}
				if($pwd != $pwd1) {
					throw new community_exception('两次密码输入不一致，请重新输入');
				}
				$row = $row->register();
				$this->_setOauthRow($row, $source);
				system_db::getAdapter()->commit();
				
				$this->_login($row, $secure, $expires);
				$this->_redirector($this->referer);
			} catch (Exception $e) {
				system_db::getAdapter()->rollBack();
				$this->view->exception = $e;
			}
		}
		$this->view->row = $row;
		$this->view->referer = $this->referer;
		$this->render();
	}
	
	public function action_logout() {
		system_passport_instance::getInstance()->getSession()->logout();
		$this->_redirector($this->referer);
	}
	
	public function action_login() {
		$this->_crumbs()->addPage(system_nav_page::create($this->language('登录'))->setRoute('account/login'));
		$concept = new community_member_concept($this->lang);
		$row = $concept->create();
		$this->view->account = '';
		$this->view->expires = 1;
		if($this->getRequest()->isPost()) {
			$source = null;
			$this->referer = $this->_post('referer');
			if(1 && $clientSource = $this->_post('oauth')) {
				$this->view->source = $source = new system_setting_oauth($clientSource);
			}
			$this->view->access_token = $this->_post('access_token');
			$this->view->avatar = $this->_post('avatar');
			$this->view->uid = $this->_post('uid');
			$this->view->expires = $expires = intval($this->_post('expires'));
			try {
				system_db::getAdapter()->beginTransaction();
				$this->view->account = $email = trim($this->_post('account'));
				$pwd = $this->_post('password');
				$ip = $this->getRequest()->getClientIp(true);
				$secure = $this->_post('secure');
				$gender = intval($this->_post('gender'));
				
				$row->setIdentity($email);
				$row->setCredential(md5($pwd));
				$row->setSecure($secure);
				$row->setGender($gender);
				$row->setLastupip($ip);
				$row = $row->login();
				$this->_setOauthRow($row, $source);
				system_db::getAdapter()->commit();
				
				$this->_login($row, $secure, $expires);
				$this->_redirector($this->referer);
			} catch (Exception $e) {
				system_db::getAdapter()->rollBack();
				$this->view->exception = $e;
			}
		}
		$this->view->referer = $this->referer;
		$this->view->row = $row;
		$this->render('account/signup.phtml');
	}
	
	public function action_oauth() {
		$client = $this->_oauth();
		if(1 && $code = $this->_get('code')) {
 			$auth = $client->authorize();
			$error = $auth->getError();
			if(!empty($error)) {
				echo implode(';', $error);exit;
				throw new front_exception(implode(';', $error));
			}
 			$token = $client->getToken();
 			$concept = new community_oauth_concept($client->getSource()->getKey());
 			if(1 && $oauth = $concept->fetch(array('access_token = ?' => $token->getAccessToken()))) {
				$oauth->setAppId($token->getAppId());
				$oauth->setAppKey($token->getAppKey());
				$oauth->setUid($client->request()->getUid());
				$oauth->setExpiredtime(system_date::timestamp() + $token->getExpires());
				$oauth->save();
				
				if(!($memberRow = $oauth->getMember($this->lang))) {
					$pRow = $oauth->getPassport();
					$mConcept = new community_member_concept($this->lang);
					$memberRow = $mConcept->create();
					$memberRow->setIdentity($pRow->getIdentity());
					$memberRow->setCredential($pRow->getCredential());
					$memberRow->setLastupip($this->getRequest()->getClientIp(true));
					$memberRow = $memberRow->login();					
				}
				
				$this->_login($memberRow, false, $token->getExpires());
				$this->_redirector($client->getCallback());
 			} else {
 				//如果已经登录..
 				if($this->user) {
					$oauth = $concept->create();
					$oauth->setPassportId($this->user->getId());
					$oauth->setAccessToken($token->getAccessToken());
					$oauth->setUid($client->request()->getUid());
					$oauth->setAppId($token->getAppId());
					$oauth->setAppKey($token->getAppKey());
					$oauth->setAttribute($token);
					$oauth->setCreationip($this->getRequest()->getClientIp(true));
					$oauth->setExpiredtime(system_date::timestamp() + $token->getExpires());
					$oauth->save();
					$this->_redirector($client->getCallback());
 				} else {
 					$this->_redirector($auth->getRedirectUrl(false) . '?auth=signin');
 				}
 			}
		} elseif($this->_get('auth') == 'signin') {
			$this->_crumbs()->addPage(
					system_nav_page::create($this->language('完成登录'))
							->setRoute('account/oauth')
							->setParams($this->getRequest()->getParams())
							->setQuery($this->_get())
			);
			$ui = $client->request();
			$concept = new community_member_concept($this->lang);
			$row = $concept->create();
			$row->setNickname($ui->getNickname());
			$row->setGender($ui->getGender());
			$this->view->expires = 1;
			$this->view->referer = $client->getCallback();
			$this->view->access_token = $client->getToken()->getAccessToken();
			$this->view->source = $client->getSource();
			$this->view->avatar = $ui->getAvatar();
			$this->view->uid = $ui->getUid();
			$this->view->row = $row;
			try {
				$error = $ui->getError();
				if(!empty($error)) {
					throw new front_exception(implode(';', $error));
				}
			} catch (Exception $e) {
				$this->view->throwException = $e;
			}
			$this->render('account/signup.phtml');
		} else {
			$this->_redirector($client->setCallback($this->referer)->url());
		}
	}
	
	/**
	 *
	 * @return oauth_open_qzone
	 */
	private function _oauth() {
		$name = strtolower(trim($this->_param('name')));
		$class = 'oauth_open_' . $name;
		return new $class();
	}
	
	private function _setOauthRow(community_member_row $row, $source) {
		$ip = $this->getRequest()->getClientIp(true);
		if($source instanceof system_setting_oauth) {
			$class = 'oauth_open_' . strtolower($source->getKey());
			$client = new $class();
			$token = $client->getToken();
			$authConcept = new community_oauth_concept($source->getKey());
			$authRow = $authConcept->create();
			$authRow->setPassportId($row->getPassportId());
			$authRow->setAccessToken($token->getAccessToken());
			$authRow->setUid(trim($this->_post('uid')));
			$authRow->setAppId($token->getAppId());
			$authRow->setAppKey($token->getAppKey());
			$authRow->setAttribute($token);
			$authRow->setCreationip($ip);
			$authRow->setExpiredtime(system_date::timestamp() + $token->getExpires());
			$authRow->save();
		
			try {
				$resRow = resource_api_avatar::createRemote($this->_post('avatar'));
			} catch (Exception $e) {
				$resRow = null;
			}
			if($resRow) {
				$resRow->save();
				
				$avatarConcept = new community_member_avatar_concept();
				$avatarRow = $avatarConcept->create();
				$avatarRow->setPassportId($row->getPassportId());
				$avatarRow->setHash($resRow->getHash());
				$avatarRow->setCreationip($ip);
				$avatarRow->save();
				
				if(!preg_match('/^[0-9a-z]{32}$/i', $row->get('avatar'))) {
					$row->setAvatar($resRow->getHash());
					$row->update();
				}
			}
		}
	}
	
	private function _login(community_member_row $row, $secure = false, $expires = null) {
		if($secure === true) {
			$row->setSecure(md5(system_session::getId()));
			$row->update();
		}
		$login = system_passport_instance::getInstance()->getSession()
				->setId($row->getId())
				->setIdentity($row->getIdentity())
				->setSecurity($secure);
		if($expires) {
			$login->setExpirationSeconds($expires);
		}	
	}

}
